//
//  arcAssignDetailEGAViewController.m
//  EGA_Archives_iOS
//
//  Created by gad on 1/25/56 BE.
//  Copyright (c) 2556 EGA. All rights reserved.
//
#import "EGAAppDelegate.h"
#import "arcAssignDetailEGAViewController.h"
#import "popOverDatePicker.h"
#import "ARC_DB.h"
#import "EGAEmployeeInfo.h"
#import "TokenFieldExampleViewController.h"
#import "Names.h"
#import "EGAUtility.h"

#import <QuartzCore/QuartzCore.h>

@interface arcAssignDetailEGAViewController ()
{
    NSMutableArray *productArray;
    UIViewController* popoverContent;
    UIView *popoverView;
    UIView *desView;
    UIView *popoverSearchEmpView;
    popOverDatePicker *dateController;
    UIPopoverController *popoverController;
     UIPopoverController *descriptionController;
    UIPopoverController *_popoverEmai;
    UIDatePicker *datePicker;
    UILabel *lblDes;
    NSString *date;
    NSString *tmpMail;

}

@end

@implementation arcAssignDetailEGAViewController
@synthesize popoverEmail=_popoverEmai;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad

{
  
    [super viewDidLoad];
    
    
    
    [self setviewLoading];
    
    
    
    [self checkRoleManagerForDisableCommand];
    
    
    
    ARC_DB * DB = [[ARC_DB alloc]init];
    if (![DB isHasEmpdataDB])
    {
      [DB saveEmpData];
    }
    
    
	[self.navigationItem setTitle:@"Example"];
    CGRect b = CGRectMake(188, 75, 520, 90);
    tokenFieldView = [[TITokenFieldView alloc] initWithFrame: b];

    	[tokenFieldView setSourceArray:[DB getEmpdata]];
    

    
	[_viewCommandSection addSubview:tokenFieldView];
    TIToken * token ;
    if ([self.empEmail isEqualToString:@""]==FALSE) {
        
    
     NSArray *array = [self.empEmail componentsSeparatedByString:@","];
      NSLog(@"array.count%d",array.count);
    NSLog(@"self.empEmail%@",self.empEmail);
    NSInteger length= [self.empEmail length];
    if (length>0) {
        if (array.count>1){
            for (NSInteger i=0; i<array.count; i++) {
                token  = [[TIToken alloc] initWithTitle:array[i]];
                [ tokenFieldView.tokenField  addToken:token];
          
            }
        }else{
            token  = [[TIToken alloc] initWithTitle:self.empEmail];
            [ tokenFieldView.tokenField  addToken:token];
             
          
        }
    }
 
        
        [tokenFieldView.tokenField resignFirstResponder];


 
        
    [token release];
      [tokenFieldView release];
    }

    
    
    self.scollVIew.layer.borderColor = [UIColor colorWithRed:0/255.0 green: 100/255.0 blue:0/255.0 alpha:1].CGColor;
    self.scollVIew.layer.borderWidth =  0.5;
    self.scollVIew.layer.cornerRadius=5;
    
    
  
    int len = [self.Doc_Subject length];
    NSLog(@"led%d",len);
    if ( len < 160 ){
         _subjectImagePop.hidden=YES;
    }
    if (len > 80){
      [_btb_subject setFrame:CGRectMake(148, 55, 510,45)];
        
    }
    else
    {
       [_btb_subject setFrame:CGRectMake(148, 57, 510,25)];
       
    }
     len = [self.Doc_Description length];
    if (len < 50){
        _desImagePop.hidden=YES;
    }
   
    _txt_subject.text =self.Doc_Subject; //[NSString stringWithFormat:@"%d",len];;   //self.Doc_Subject;
    _txt_subject.userInteractionEnabled=YES;
    
    UILabel *buttonLabel = [[UILabel alloc] initWithFrame:_btb_subject.bounds];
 
    buttonLabel.numberOfLines = 2;
    buttonLabel.text = self.Doc_Subject;
     [buttonLabel setTextColor:[UIColor darkGrayColor]];
    [_btb_subject addSubview:buttonLabel];
    [_btb_subject bringSubviewToFront:buttonLabel];
    
        _txt_subject.tag=0;
    lblDocToName.text=self.DocToName;
    lblOrg_Name.text=self.Org_Name;
    lblDoc_Register.text=self.Doc_Register;
    lblDoc_serial.text=self.Doc_Serial;
    
    
    
    EGAUtility * Util = [[EGAUtility alloc]init];
    NSString *convertedString=[Util getDateTh:(self.Doc_date)];
    
    lblDoc_date.text=convertedString;//self.Doc_date;
    
    _txt_Description.text = self.Doc_Description;
    _txt_Description.tag=1;

    
    lblDoc_Priority.text = self.Doc_Priority_Name;
    convertedString=[Util getDateTh:(self.Doc_ReceiveDate)];
    lblDoc_ReceiveDate.text = convertedString;//self.Doc_ReceiveDate;
    
    _lblTitle.text = [NSString stringWithFormat:@"[สั่งการ] %@",self.Doc_Subject];
    
    tmpMail = self.empEmail;
    _txtSendTo.text=self.empEmail;
    _tesFile.text=self.taskDetail;

    
 
    switch([self.DocPriorityID intValue]) {
        case 4:
            [self setSelectedButton:_radioButton1];
            break;
        case 3:
             [self setSelectedButton:_radioButton2];
            break;
        case 2:
            [self setSelectedButton:_radioButton3];
            break;
        case 1:
            [self setSelectedButton:_radioButton4];
            break;
        default:
            [self setSelectedButton:_radioButton4];
            break;
    }
     if ([_IsDueDate isEqualToString:@"true"]) {
         UIImage *image = [UIImage imageNamed:@"checkBoxChecked.png"];
         [_checkboxButton setBackgroundImage:image forState:UIControlStateNormal];
         [_checkboxButton setBackgroundImage:image forState:UIControlStateSelected];
         [_checkboxButton setBackgroundImage:image forState:UIControlStateHighlighted];
         _checkboxButton.adjustsImageWhenHighlighted = YES;
         _checkboxButton.selected = NO;
                  
        }else{
                 UIImage *image = [UIImage imageNamed:@"checkBoxUnchecked.png"];
                 [_checkboxButton setBackgroundImage:image forState:UIControlStateNormal];
                 [_checkboxButton setBackgroundImage:image forState:UIControlStateSelected];
                 [_checkboxButton setBackgroundImage:image forState:UIControlStateHighlighted];
                 _checkboxButton.adjustsImageWhenHighlighted = YES;
                 _checkboxButton.selected = YES;
               

     }

    dateController = [[popOverDatePicker alloc] initWithNibName:@"popOverDatePicker" bundle:nil];   
    popoverView = [[UIView alloc] init];   //view
    popoverView.backgroundColor = [UIColor blackColor];
    
    datePicker=[[UIDatePicker alloc]init];//Date picker
    datePicker.datePickerMode =UIDatePickerModeDate;
    

  
    [datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
    [popoverView addSubview:datePicker];
    
    
    popoverController = [[UIPopoverController alloc] initWithContentViewController:dateController];
    [popoverController setPopoverContentSize:CGSizeMake(320, 216) animated:NO];
    dateController.view=popoverView;
    
    [dateController release];
    
    //descriptionController
 
 //   [descriptionController setPopoverContentSize:CGSizeMake(320, 216) animated:NO];
    
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"YYYY-MM-dd"];

    if ([self.startDate isEqualToString:NULL]) {

            self.lblEndDate.text= [dateFormat stringFromDate:self.startDate];
        self.lblStartDate.text= [dateFormat stringFromDate:self.endDate];
    }
else{
        
    NSDate *now = [[NSDate alloc] init];
    self.lblEndDate.text= [dateFormat stringFromDate:now];
    self.lblStartDate.text= [dateFormat stringFromDate:now];

}
    self.lblEndDate.tag=0;
    self.lblStartDate.tag=1;
    
    
    [self setButtonToShowFile];
    

    

}



-(EGAAppDelegate*)appDelegate
{
    return  (EGAAppDelegate*)[[UIApplication sharedApplication] delegate];
}
-(void)checkRoleManagerForDisableCommand
{
    NSString *RoleName = self.appDelegate.employeeInfo.RoleName;
    if([RoleName isEqualToString:@"manager"])
    {
        _viewCommandSection.hidden = YES;
    }
}










-(void)setviewLoading
{
    viewLoading = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    viewLoading.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.25];
    UIActivityIndicatorView * activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
    activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake((self.view.frame.size.width/2) - 60, (self.view.frame.size.height/2) - 40, 150, 120)];
    activityIndicator.backgroundColor=[UIColor colorWithRed:105/255.0 green: 105/255.0 blue:105/255.0 alpha:1];
    [activityIndicator layer].cornerRadius = 8.0;
    [activityIndicator startAnimating];
    [viewLoading addSubview:activityIndicator];
    
    UILabel * activityLabel = [[UILabel alloc] init];
    activityLabel.text = NSLocalizedString(@"Loading..", @"string1");
    activityLabel.textColor = [UIColor whiteColor];
    activityLabel.font = [UIFont boldSystemFontOfSize:20];
    activityLabel.backgroundColor=[UIColor clearColor];
    activityLabel.frame=CGRectMake((self.view.frame.size.width/2) - 60, (self.view.frame.size.height/2) , 150, 100);
    activityLabel.textAlignment = UITextAlignmentCenter;
    [viewLoading addSubview:activityLabel];
    
    [self.view addSubview:viewLoading];
    [self hideLoadingView];
}


-(void)showLoadingView
{
    [self.view.superview insertSubview:viewLoading aboveSubview:self.view];
}

-(void)hideLoadingView
{
    [viewLoading performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];
}


- (IBAction)showSubjectPopoverDetail:(id)sender {
     CGRect popRect ;
    popoverContent = [[UIViewController alloc] init];
    
    popoverView = [[UIView alloc] initWithFrame:popRect];
    popoverView.backgroundColor = [UIColor whiteColor];
    popoverContent.view = popoverView;
    popoverContent.contentSizeForViewInPopover = CGSizeMake(500, 150);
    UIPopoverController *desPop = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
    UITextView *stw=[[UITextView alloc] initWithFrame:CGRectMake(10, 10, 500, 150)];
    [stw setTextColor:[UIColor darkGrayColor]];
    stw.backgroundColor = [UIColor clearColor];
    
 
    [popoverView addSubview:stw];
    
    [popoverContent release];
    popRect = CGRectMake(123,160,_btb_subject.frame.size.width,_btb_subject.frame.size.height);
     
    stw.font = [UIFont systemFontOfSize:17.0];
    stw.text=self.Doc_Subject;
    [stw setTextColor:[UIColor darkGrayColor]];
  
 //   int len = [self.Doc_Subject length];
  //  if (len > 160){
         [desPop presentPopoverFromRect:popRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
   // }

}








-(void)setButtonToShowFile
{
    //book
    NSArray *arrDocBookBeforeSign_ID    = [self.DocBookBeforeSign_ID componentsSeparatedByString:@";"];
    NSArray *arrDocBookBeforeSign_Name  = [self.DocBookBeforeSign_Name componentsSeparatedByString:@";"];
    
    if([arrDocBookBeforeSign_ID count]!=0 && ![arrDocBookBeforeSign_ID[0] isEqualToString:@"<null>"])
    {
        for(int i = 0; i <= [arrDocBookBeforeSign_ID count]-1 ; i++)
        {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            if (i == 0)
                [button setFrame:CGRectMake(187, 268, 100,25 )];
            else
                [button setFrame:CGRectMake(((i+1)*100)+87, 268, 100, 25 )];
            [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            
            NSString * strBtnTitle = [NSString stringWithFormat:@" %@  ",arrDocBookBeforeSign_Name[i]];
            [button setTitle:strBtnTitle forState:UIControlStateNormal];
            
            [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
            button.accessibilityLabel = [NSString stringWithFormat:@"%@|%@",arrDocBookBeforeSign_ID[i],arrDocBookBeforeSign_Name[i]];
            
            //set button image
            NSArray     * arrFileInfo           = [button.accessibilityLabel componentsSeparatedByString:@"|"];
            NSString    * fileID                = arrFileInfo[0];
            NSString    * fileNameAndType       = arrFileInfo[1];
            NSArray     * arrFileNameAndType    = [fileNameAndType componentsSeparatedByString:@"."];
            NSString    * fileType              = arrFileNameAndType[   [arrFileNameAndType count]-1   ];
            NSString    *  storeFileName = [NSString stringWithFormat:@"%@%@.%@",@"task",fileID,fileType];
            UIImage *img ;
            if([self isHasFileWithSavedFileName:storeFileName])
                img = [UIImage imageNamed:@"open.png"];
            else
                img = [UIImage imageNamed:@"save.png"];
            
            [button setImage:img forState:UIControlStateNormal];
            
            button.titleLabel.font = [UIFont systemFontOfSize:13];
            
            [self.view addSubview:button];
            
        }
        
    }
    
    
    
    
    
    //attachment
    NSArray *arrDocAttachment_ID    = [self.DocAttachment_ID componentsSeparatedByString:@";"];
    NSArray *arrDocAttachment_Name  = [self.DocAttachment_Name componentsSeparatedByString:@";"];
    
    if([arrDocAttachment_ID count]!=0 && ![arrDocAttachment_ID[0] isEqualToString:@"<null>"])
    {
        for(int i = 0; i <= [arrDocAttachment_ID count]-1 ; i++)
        {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            if (i == 0)
                [button setFrame:CGRectMake(187, 296, 100,25 )];
            else
                [button setFrame:CGRectMake(((i+1)*100)+87, 296, 100, 25 )];
            [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            
            NSString * strBtnTitle = [NSString stringWithFormat:@" %@  ",arrDocAttachment_Name[i]];
            [button setTitle:strBtnTitle forState:UIControlStateNormal];
            
            [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
            button.accessibilityLabel = [NSString stringWithFormat:@"%@|%@",arrDocAttachment_ID[i],arrDocAttachment_Name[i]];
            
            //set button image
            NSArray     * arrFileInfo           = [button.accessibilityLabel componentsSeparatedByString:@"|"];
            NSString    * fileID                = arrFileInfo[0];
            NSString    * fileNameAndType       = arrFileInfo[1];
            NSArray     * arrFileNameAndType    = [fileNameAndType componentsSeparatedByString:@"."];
            NSString    * fileType              = arrFileNameAndType[   [arrFileNameAndType count]-1   ];
            NSString    *  storeFileName = [NSString stringWithFormat:@"%@%@.%@",@"task",fileID,fileType];
            UIImage *img ;
            if([self isHasFileWithSavedFileName:storeFileName])
                img = [UIImage imageNamed:@"open.png"];
            else
                img = [UIImage imageNamed:@"save.png"];
            
            [button setImage:img forState:UIControlStateNormal];
            
            button.titleLabel.font = [UIFont systemFontOfSize:13];
            
            [self.view addSubview:button];
            
        }
        
    }
}




- (void)buttonPressed:(UIButton *)sender
{
    self.SFVC = [[showFileVC alloc] initWithNibName:@"showFileVC" bundle:nil];
    
    self.SFVC.fileInfo = sender.accessibilityLabel;
    self.SFVC.TalkOrTask = @"task";
    [self presentPopupViewController:self.SFVC animationType:0 popupType:@"showFileTask"];
}



-(BOOL)isHasFileWithSavedFileName:(NSString*)savedFileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:savedFileName];
    
    //if file not exist in document
    if([fileManager fileExistsAtPath:writablePath])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


-(void)UpdateEmail
{
    

}
-(void)setSelectedButton:(UIButton *)radioButton{
    UIImage *image = [UIImage imageNamed:@"bt_circleClick.png"]; //the radioButton image when selected
    if(radioButton == _radioButton1){
        [_radioButton1 setBackgroundImage:image forState:UIControlStateNormal];
        [_radioButton1 setBackgroundImage:image forState:UIControlStateSelected];
        [_radioButton1 setBackgroundImage:image forState:UIControlStateHighlighted];
        _radioButton1.adjustsImageWhenHighlighted = YES;
        
        [_radioButton2 setBackgroundImage:nil forState:UIControlStateNormal];
        [_radioButton2 setBackgroundImage:nil forState:UIControlStateDisabled];
        [_radioButton2 setBackgroundImage:nil forState:UIControlStateHighlighted];
        [_radioButton2 setBackgroundImage:nil forState:UIControlStateSelected];
        [_radioButton3 setBackgroundImage:nil forState:UIControlStateNormal];
        [_radioButton3 setBackgroundImage:nil forState:UIControlStateDisabled];
        [_radioButton3 setBackgroundImage:nil forState:UIControlStateHighlighted];
        [_radioButton4 setBackgroundImage:nil forState:UIControlStateSelected];
        [_radioButton4 setBackgroundImage:nil forState:UIControlStateNormal];
        [_radioButton4 setBackgroundImage:nil forState:UIControlStateDisabled];
        [_radioButton4 setBackgroundImage:nil forState:UIControlStateHighlighted];
        [_radioButton4 setBackgroundImage:nil forState:UIControlStateSelected];
        
        _radioButton1.enabled = NO;
        _radioButton2.enabled = YES;
        _radioButton3.enabled = YES;
        _radioButton4.enabled = YES;
    }else if(radioButton == _radioButton2){
        [_radioButton2 setBackgroundImage:image forState:UIControlStateNormal];
        [_radioButton2 setBackgroundImage:image forState:UIControlStateSelected];
        [_radioButton2 setBackgroundImage:image forState:UIControlStateHighlighted];
        _radioButton2.adjustsImageWhenHighlighted = YES;
        
        [_radioButton1 setBackgroundImage:nil forState:UIControlStateNormal];
        [_radioButton1 setBackgroundImage:nil forState:UIControlStateDisabled];
        [_radioButton1 setBackgroundImage:nil forState:UIControlStateHighlighted];
        [_radioButton1 setBackgroundImage:nil forState:UIControlStateSelected];
        [_radioButton3 setBackgroundImage:nil forState:UIControlStateNormal];
        [_radioButton3 setBackgroundImage:nil forState:UIControlStateDisabled];
        [_radioButton3 setBackgroundImage:nil forState:UIControlStateHighlighted];
        [_radioButton3 setBackgroundImage:nil forState:UIControlStateSelected];
        [_radioButton4 setBackgroundImage:nil forState:UIControlStateNormal];
        [_radioButton4 setBackgroundImage:nil forState:UIControlStateDisabled];
        [_radioButton4 setBackgroundImage:nil forState:UIControlStateHighlighted];
        [_radioButton4 setBackgroundImage:nil forState:UIControlStateSelected];

        
        _radioButton1.enabled = YES;
        _radioButton2.enabled = NO;
        _radioButton3.enabled = YES;
        _radioButton4.enabled = YES;

    }else if(radioButton == _radioButton3){
        [_radioButton3 setBackgroundImage:image forState:UIControlStateNormal];
        [_radioButton3 setBackgroundImage:image forState:UIControlStateSelected];
        [_radioButton3 setBackgroundImage:image forState:UIControlStateHighlighted];
        _radioButton3.adjustsImageWhenHighlighted = YES;
        
        [_radioButton1 setBackgroundImage:nil forState:UIControlStateNormal];
        [_radioButton1 setBackgroundImage:nil forState:UIControlStateDisabled];
        [_radioButton1 setBackgroundImage:nil forState:UIControlStateHighlighted];
        [_radioButton1 setBackgroundImage:nil forState:UIControlStateSelected];
        [_radioButton2 setBackgroundImage:nil forState:UIControlStateNormal];
        [_radioButton2 setBackgroundImage:nil forState:UIControlStateDisabled];
        [_radioButton2 setBackgroundImage:nil forState:UIControlStateHighlighted];
        [_radioButton2 setBackgroundImage:nil forState:UIControlStateSelected];
        [_radioButton4 setBackgroundImage:nil forState:UIControlStateNormal];
        [_radioButton4 setBackgroundImage:nil forState:UIControlStateDisabled];
        [_radioButton4 setBackgroundImage:nil forState:UIControlStateHighlighted];
        [_radioButton4 setBackgroundImage:nil forState:UIControlStateSelected];

        
        _radioButton1.enabled = YES;
        _radioButton2.enabled = YES;
        _radioButton3.enabled = NO;
        _radioButton4.enabled = YES;


    }else{
        [_radioButton4 setBackgroundImage:image forState:UIControlStateNormal];
        [_radioButton4 setBackgroundImage:image forState:UIControlStateSelected];
        [_radioButton4 setBackgroundImage:image forState:UIControlStateHighlighted];
        _radioButton4.adjustsImageWhenHighlighted = YES;
        
        [_radioButton1 setBackgroundImage:nil forState:UIControlStateNormal];
        [_radioButton1 setBackgroundImage:nil forState:UIControlStateDisabled];
        [_radioButton1 setBackgroundImage:nil forState:UIControlStateHighlighted];
        [_radioButton1 setBackgroundImage:nil forState:UIControlStateSelected];
        [_radioButton2 setBackgroundImage:nil forState:UIControlStateNormal];
        [_radioButton2 setBackgroundImage:nil forState:UIControlStateDisabled];
        [_radioButton2 setBackgroundImage:nil forState:UIControlStateHighlighted];
        [_radioButton2 setBackgroundImage:nil forState:UIControlStateSelected];
        [_radioButton3 setBackgroundImage:nil forState:UIControlStateNormal];
        [_radioButton3 setBackgroundImage:nil forState:UIControlStateDisabled];
        [_radioButton3 setBackgroundImage:nil forState:UIControlStateHighlighted];
        [_radioButton3 setBackgroundImage:nil forState:UIControlStateSelected];
        
        _radioButton1.enabled = YES;
        _radioButton2.enabled = YES;
        _radioButton3.enabled = YES;
        _radioButton4.enabled = NO;
    }

}
-(IBAction)radioButton1Selected{
    [self setSelectedButton:_radioButton1];
}
-(IBAction)radioButton2Selected{
    [self setSelectedButton:_radioButton2];
}
-(IBAction)radioButton3Selected{
    [self setSelectedButton:_radioButton3];
}
-(IBAction)radioButton4Selected{
    [self setSelectedButton:_radioButton4];
}

- (IBAction)dateOfBirthButtonPressed:(id)sender {
    }

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(IBAction)popOverPicker:(id)sender   {
     
    if ([popoverController isPopoverVisible]) {
        [popoverController dismissPopoverAnimated:YES];
    } else {
        //the rectangle here is the frame of the object that presents the popover,
        //in this case, the UIButton…
        CGRect popRect = CGRectMake(self.bntpopOverPickerShow.frame.origin.x,
                                    self.bntpopOverPickerShow.frame.origin.y,
                                    self.bntpopOverPickerShow.frame.size.width,
                                    self.bntpopOverPickerShow.frame.size.height);
        [popoverController presentPopoverFromRect:popRect
                                           inView:self.view
                         permittedArrowDirections:UIPopoverArrowDirectionAny
                                         animated:YES];
    }
}
- (void)dealloc {
//    [lblDoc_Subject release];
    [lblDocToName release];
    [lblOrg_Name release];
    [lblDoc_Register release];
    [lblDoc_date release];
    [lblDoc_serial release];
    
    
    
     
    
    [_txtOrderDetail release];
    [_radioButton1 release];
    [_radioButton2 release];
    [_radioButton3 release];
    [_radioButton4 release];
    
    [_lblStartDate release];
   
    
    [_tesFile release];
    [_lblStartDate release];
    [_lblEndDate release];
    
    [datePicker release];
    //[_btSearch release];
 
    [_txtSendTo release];
    //[_labelTest release];
    [_scollVIew release];
    [_btSumint release];
    
    [_activeSubmit release];

    [lblDoc_ReceiveDate release];
  //  [lblDoc_Description release];
    [_lblTitle release];
    [_viewCommandSection release];
    [lblDoc_serial release];
    
    [_txt_Description release];
    [_btb_subject release];
    [_subjectImagePop release];
    [_desImagePop release];
    [_btPopSub release];
    [_btDesPop release];
 
    [super dealloc];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    CGRect popRect ;
   if ([textField isEqual:self.lblStartDate]||[textField isEqual:self.lblEndDate]) {
        if ([popoverController isPopoverVisible]) {
            [popoverController dismissPopoverAnimated:YES];
        } else {
             switch (textField.tag)
            {
                 case 1:
                     
                      popRect = CGRectMake(160,730,self.lblStartDate.frame.size.width,self.lblStartDate.frame.size.height);
                      date=@"1";
                 break;
                 case  0:
                      popRect = CGRectMake(160,770,self.lblEndDate.frame.size.width,self.lblEndDate.frame.size.height);
                      date=@"0";
                 break;
                default:
                    
                    break;
                     // remainder of switch statement....
             }
            [popoverController presentPopoverFromRect:popRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

            
        }
            
         return NO;
    }
    if ([textField isEqual:self.txt_Description]||[textField isEqual:self.txt_subject]) {
        NSLog(@"Doc_Description");
        popoverContent = [[UIViewController alloc] init];
       
        popoverView = [[UIView alloc] initWithFrame:popRect];
        popoverView.backgroundColor = [UIColor whiteColor];
        popoverContent.view = popoverView;
        popoverContent.contentSizeForViewInPopover = CGSizeMake(500, 150);
        UIPopoverController *desPop = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
        UITextView *stw=[[UITextView alloc] initWithFrame:CGRectMake(10, 10, 500, 150)];
        stw.backgroundColor = [UIColor clearColor];
       stw.font = [UIFont systemFontOfSize:17.0];
//        [test presentPopoverFromRect:popRect inView:self.view  permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES];
        [popoverView addSubview:stw];

        [popoverContent release];
        if ([desPop isPopoverVisible]) {
            [desPop dismissPopoverAnimated:YES];
        } else {
            switch (textField.tag)
            {
                case 1:
                    
                   popRect = CGRectMake(123,330,_txt_Description.frame.size.width,_txt_Description.frame.size.height);
                   stw.text=self.Doc_Description;
                    break;
                case  0:
//                     popRect = CGRectMake(123,160,_txt_subject.frame.size.width,_txt_subject.frame.size.height);
//                      stw.text=self.Doc_Subject;
                    break;
                default:
                    
                    break;
                    // remainder of switch statement....
            }
//            int len = [self.Doc_Description length];
//            if (len > 80){
             [desPop presentPopoverFromRect:popRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
     //       }
            
        }
        
        return NO;

      }

    return YES;

}
- (IBAction)dateChanged:(id)sender {
   //  NSLog(@"dateChanged");
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     [dateFormatter setDateFormat:@"YYYY-MM-dd"];
     
    
    if (date==@"1")  
            self.lblStartDate.text= [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:datePicker.date]];
        else
            self.lblEndDate.text= [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:datePicker.date]];
   
   
}
- (CGRect)pickerFrameWithSize:(CGSize)size
{
    CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
    CGRect pickerRect = CGRectMake( 0.0,
                                   screenRect.size.height - 42.0 - size.height,
                                   size.width,
                                   size.height);
    return pickerRect;
}

- (void)dismiss:(NSString *)email {
    
    NSLog(@"dismiss");
}

- (IBAction)sumbit:(id)sender {
    
    
    [NSThread detachNewThreadSelector:@selector(showLoadingView) toTarget:self withObject:nil ];
    sleep(2.0);

    
   
    NSString *emai=@"";
    ARC_DB * DB = [[ARC_DB alloc]init];
    /// unique
    NSMutableArray * unique = [NSMutableArray array];
    NSMutableSet * processed = [NSMutableSet set];
    for (NSString * string in tokenFieldView.tokenTitles) {
        if ([processed containsObject:string] == NO) {
            [unique addObject:string];
            [processed addObject:string];
        }
    }
    // find email in [DB getEmpdata]
    NSMutableArray *empEmail=[DB getEmpdata];
    NSInteger empCount=0;
    for (NSInteger i=0; i<unique.count; i++) {
        BOOL isTheObjectThere = [empEmail containsObject:unique[i]];
        if (isTheObjectThere) {
            
            if (empCount<1)
                emai = unique[i];
            else
                emai = [NSString stringWithFormat:@"%@%@%@",emai,@",",unique[i]];
            empCount++;
        }
        
    }
    
            NSString *priorityDoc,*IsDueDate ;
            if(self.radioButton1.enabled==NO)
                priorityDoc=@"4";
            if(self.radioButton2.enabled==NO)
                priorityDoc=@"3";
            if(self.radioButton3.enabled==NO)
                priorityDoc=@"2";
            if(self.radioButton4.enabled==NO)
                priorityDoc=@"1";
            
            IsDueDate=@"false";
            if(self.checkboxButton.selected==NO)
                IsDueDate=@"true";

//            NSString *jsonURL=[NSString stringWithFormat:@"http://%@AssignTask.ashx",serviceUrl];
//    
//            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: jsonURL]];
//            NSString * fullName = [NSString stringWithFormat:@"%@ %@",self.appDelegate.employeeInfo.FirstNameTH,self.appDelegate.employeeInfo.LastNameTH];
//            
//            NSString * fullNameUTF8 = [fullName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//            NSString *post = [NSString stringWithFormat:@"documentListID=%@&empMail=%@&description=%@&StartDate=%@&EndDate=%@&DocPriorityID=%@&IsDueDate=%@&myname=%@",self.ID
//                              ,emai,[self.tesFile.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],self.lblStartDate.text,self.lblEndDate.text,priorityDoc,IsDueDate,fullNameUTF8 ];
//
//            NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//            
//            NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
//            [request setHTTPMethod:@"POST"];
//            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//            [request setHTTPBody:postData];
//            
//            
//            NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
//
    
    
    /////////////////new
    EGAUtility * Util = [[EGAUtility alloc]init];
    NSString * fullName = [NSString stringWithFormat:@"%@ %@",self.appDelegate.employeeInfo.FirstNameTH,self.appDelegate.employeeInfo.LastNameTH];
    NSString * fullNameUTF8 = [fullName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *post = [NSString stringWithFormat:@"documentListID=%@&empMail=%@&description=%@&StartDate=%@&EndDate=%@&DocPriorityID=%@&IsDueDate=%@&myname=%@",self.ID,emai,[self.tesFile.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],self.lblStartDate.text,self.lblEndDate.text,priorityDoc,IsDueDate,fullNameUTF8 ];
    NSString *strURL=[NSString stringWithFormat:@"ws=AssignTask.ashx&%@",post];
    NSData *returnData =[Util getDataFromService:strURL];
    /////////////////newf
    
    
    
            if ([returnData length] == 0) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"ไม่สามารถเชื่อมต่อ server" message:@"กรุณาเช็คการเชื่อมต่อ" delegate:self cancelButtonTitle:@"ตกลง" otherButtonTitles: nil];
                [alert show];
                [self hideLoadingView];
                return;
            }
            
            

            [DB uddateBookList:self.ID empMail:emai description:self.tesFile.text  StartDate:self.lblStartDate.text EndDate:self.lblEndDate.text DocPriorityID:priorityDoc IsDueDate:IsDueDate];
 
           
            
            // alert command success
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"สำเร็จ"
                                                            message:@"สั่งการเรียบร้อยแล้ว"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            

    [self hideLoadingView];

}
- (void)emailSelected:(NSString *)email {
  NSLog(@"emailSelected");

}
-(IBAction)checkboxSelected:(id)sender{
    if(_checkboxButton.selected == NO){
        UIImage *image = [UIImage imageNamed:@"checkBoxUnchecked.png"];
        [_checkboxButton setBackgroundImage:image forState:UIControlStateNormal];
        [_checkboxButton setBackgroundImage:image forState:UIControlStateSelected];
        [_checkboxButton setBackgroundImage:image forState:UIControlStateHighlighted];
        _checkboxButton.adjustsImageWhenHighlighted = YES;
        _checkboxButton.selected = YES;
        NSLog(@"Checked");
    }else{
        UIImage *image = [UIImage imageNamed:@"checkBoxChecked.png"];
        [_checkboxButton setBackgroundImage:image forState:UIControlStateNormal];
        [_checkboxButton setBackgroundImage:image forState:UIControlStateSelected];
        [_checkboxButton setBackgroundImage:image forState:UIControlStateHighlighted];
        _checkboxButton.adjustsImageWhenHighlighted = YES;
        _checkboxButton.selected = NO;
        NSLog(@"Unchecked");
    }
 }
 
- (IBAction)popSubShow:(id)sender {
    CGRect popRect ;
    popoverContent = [[UIViewController alloc] init];
    
    popoverView = [[UIView alloc] initWithFrame:popRect];
    popoverView.backgroundColor = [UIColor whiteColor];
    popoverContent.view = popoverView;
    popoverContent.contentSizeForViewInPopover = CGSizeMake(500, 150);
    UIPopoverController *desPop = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
    UITextView *stw=[[UITextView alloc] initWithFrame:CGRectMake(10, 10, 500, 150)];
    [stw setTextColor:[UIColor darkGrayColor]];
    stw.backgroundColor = [UIColor clearColor];
    
    
    [popoverView addSubview:stw];
    
    [popoverContent release];
    popRect = CGRectMake(123,160,_btb_subject.frame.size.width,_btb_subject.frame.size.height);
    
    stw.font = [UIFont systemFontOfSize:17.0];
    stw.text=self.Doc_Subject;
    [stw setTextColor:[UIColor darkGrayColor]];
    
    //   int len = [self.Doc_Subject length];
    //  if (len > 160){
    [desPop presentPopoverFromRect:popRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    // }

}

- (IBAction)popDesShow:(id)sender {
    CGRect popRect ;
    popoverContent = [[UIViewController alloc] init];
    
    popoverView = [[UIView alloc] initWithFrame:popRect];
    popoverView.backgroundColor = [UIColor whiteColor];
    popoverContent.view = popoverView;
    popoverContent.contentSizeForViewInPopover = CGSizeMake(500, 150);
    UIPopoverController *desPop = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
    UITextView *stw=[[UITextView alloc] initWithFrame:CGRectMake(10, 10, 500, 150)];
    [stw setTextColor:[UIColor darkGrayColor]];
    stw.backgroundColor = [UIColor clearColor];
    
    
    [popoverView addSubview:stw];
    
    [popoverContent release];
    popRect = CGRectMake(123,330,_txt_Description.frame.size.width,_txt_Description.frame.size.height);

    
    stw.font = [UIFont systemFontOfSize:17.0];
    stw.text=self.Doc_Description;
    [stw setTextColor:[UIColor darkGrayColor]];
    
    //   int len = [self.Doc_Subject length];
    //  if (len > 160){
    [desPop presentPopoverFromRect:popRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];

}
@end
